package com.justinbuser.net
{
	import flash.errors.IOError;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.TimerEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.utils.Timer;

	public class PollingConnection
	{
		private var timer:Timer;
		private var loader:URLLoader;
		private var request:URLRequest;
		private var client:PollingClient;
		
		public function PollingConnection(urlToPoll:String, pollingClient:PollingClient, autoStart:Boolean=true, intervalDuration:Number=60, postData:Object=null)
		{
			client=pollingClient;
			request = new URLRequest(urlToPoll);
			if(postData){
				request.method="post";
				request.data=postData;
			}
			timer = new Timer(intervalDuration * 1000);			
			if(autoStart) start();
			else load();
		}
		
		public function get running():Boolean{
			return timer.running;
		}
		
		public function start():void{
			if(!running){		
				trace('starting');
				timer.addEventListener(TimerEvent.TIMER,load);
				timer.start();
				load();
			}
		}
		
		public function stop():void{
			if(running){
				timer.removeEventListener(TimerEvent.TIMER,load);
				timer.reset();
			}
		}
		
		public function load(e:TimerEvent=null):void{
			loader = new URLLoader(request);
			loader.addEventListener(Event.COMPLETE,sendData);
			loader.addEventListener(IOErrorEvent.IO_ERROR,sendError);
			
			function sendData(e:*):void{
				client.dataReceived(loader.data);
				loader.removeEventListener(Event.COMPLETE,sendData);
				loader.removeEventListener(IOErrorEvent.IO_ERROR,sendError);
			}
			
			function sendError(e:IOErrorEvent):void{
				client.connectionError(new IOError(e.text,e.errorID));	
				loader.removeEventListener(Event.COMPLETE,sendData);
				loader.removeEventListener(IOErrorEvent.IO_ERROR,sendError);
			}
			
		}
		
		
	}
}